<?php

namespace app\api\controller\store;

use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\mall\Goods;
use app\common\model\Store;
use think\Db;
use think\Exception;
use think\Log;

class Index extends Api
{
    protected $noNeedRight = '*';
    /**
     * 前置方法
     * @var string[]
     */
    protected $beforeActionList = [
        'check'
    ];

    protected $store_id;

    protected $model;

    /**
     * 检测是否是商家，平台是否通过审核
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check()
    {
        $identity = $this->auth->identity;
        if($identity !== '20'){
            $this->error('商家尚未入驻');
        }
        $this->model = new Store();
        $row = $this->model->where(['user_id'=>['=',$this->auth->id]])->order('id desc')->find();
        if($row->state !== '20'){
            $this->error('平台尚未审核通过');
        }
        $this->store_id  = $row->id;
    }

    /**
     * 商家信息
     * @return void
     */
    public function index()
    {
        try {
            $row = $this->model->where(['user_id'=>['=',$this->auth->id],'state'=>['=','20']])->field(['user_id','amount','pay_status','pay_way','reason','verifytime','total_sales','sales','false_sales','likes','collect','recommend_switch','transaction_id','refund_status','refundtime','createtime','updatetime'],true)->find();
            $this->success('success',$row);
        }catch (Exception $e){
            $this->error(__('Network error'));
        }
    }

    /**
     * 编辑商家信息
     * @return void
     */
    public function save()
    {
        try {
            $row = $this->model->get($this->store_id);
            if(empty($row)){
                $this->error(__('No results were found'));
            }
            $param = $this->request->post();
             $row->allowField(true)->save($param);
             $this->success(__('Operation completed'));
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 商品列表
     * @return void
     */
    public function goodsList()
    {
        try {
            $status = $this->request->post('status');
            $limit = $this->request->post('limit/d',10);
            $page = $this->request->post('page/d',1);
            if(!in_array($status,['10','20'])){
                $this->error(__('Invalid parameters'));
            }
            $goodsModel = new Goods();
            $list = $goodsModel->where(['status'=>['=',$status]])->field('id,name,category_id,price,market_price,coupon_switch,state')->order('id desc')->paginate($limit,false,['page'=>$page]);
            $this->success('SUCCESS',$list);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 商品详情
     * @return void
     */
    public function details()
    {
        try {
            $id = $this->request->post('id/d');
            if(empty($id)){
                $this->error(__('Invalid parameters'));
            }
            $goodsModel = new Goods();
            //'id,status,name,category_id,coupon_switch,coupon_ids,freight,image,details_text,details_images,price,market_price,artisan_free,parts_ids,cost_explain_text'
            $info = $goodsModel->where('id',$id)->field('id,status,name,category_id,coupon_switch,coupon_ids,freight,image,details_text,details_images,price,market_price,artisan_free,parts_ids,cost_explain_text')->find();
            if(empty($info)){
                $this->error(__('No results were found'));
            }
            //实物商品
            if($info->status == '10'){
                $info->sku = $info->sku;
            }
            $this->success('SUCCESS',$info);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 添加、编辑商品
     * @return void
     */
    public function saveGoods()
    {
        Db::startTrans();
        try {
            $params = $this->request->post();
            extract($params);
            //status商品类型:10=实物商品,20=服务
            if(empty($status) || empty($name) || empty($category_id) || empty($image)){
                $this->error(__('Invalid parameters') . 1);
            }
            if(!in_array($status,['10','20'])){
                $this->error(__('Invalid parameters')  . 2);
            }
            if($status == '10'){
                if(empty($params['sku'])){
                    $this->error(__('Invalid parameters')   . 3);
                }
                if(!is_array($params['sku'])){
                    $this->error(__('Unknown data format'));
                }
                $params['price'] = min(array_column($params['sku'],'price'));
            }
            if(!$params['coupon_switch']){
                $params['coupon_ids'] = $coupon_ids = '';
            }
            $params['user_id'] = $this->auth->id;
            $params['store_id'] = $this->store_id;
            $model = new Goods();
            if(isset($id) && $id){
                $model = $model->get($id);
                if(empty($model)){
                    $this->error(__('No results were found'));
                }
                //商家、商品、商品分类关联表
                $model->storecategory()->detach();
                //商家、商品、优惠券关联表
                $model->coupon()->detach();
                if($status == '10'){
                    $model->sku()->delete();
                }
            }else{
                unset($params['id']);
            }
            $result = $model->allowField(true)->save($params);
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }
            if($status == '10'){
                //型号  model   价格price  库存stock
                $model->sku()->saveAll($params['sku']);
            }
            //商家、商品、商品分类关联表
            $model->storecategory()->save($params['category_id'],['store_id'=>$this->store_id]);
            //商家、商品、优惠券关联表
            if($params['coupon_ids']) {
                $model->coupon()->attach(explode(',',$params['coupon_ids']),['store_id'=>$this->store_id]);
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success(__('Operation completed'));
    }

    /**
     * 删除商品
     * @return void
     */
    public function delGoods()
    {
        try {
            $id = $this->request->post('id/d');
            if(empty($id)){
                $this->error(__('Invalid parameters'));
            }
            $goodsModel = new Goods();
            $row = $goodsModel->get($id);
            if(empty($row)){
                $this->error(__('No results were found'));
            }
            $row->delete();
            //实物商品
            if($row->status == '10'){
                $row->sku()->delete();
            }
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 上架、下架 商品
     * @return void
     */
    public function changeState()
    {
        try {
            $id = $this->request->post('id/d');
            if(empty($id)){
                $this->error(__('Invalid parameters'));
            }
            $goodsModel = new Goods();
            $row = $goodsModel->get($id);
            if(empty($row)){
                $this->error(__('No results were found'));
            }
            $tempState = ($row->state == '10') ? '20' : '10';
            $row->state = $tempState;
            $row->save();
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }
}